<template>
  <el-form ref="formRef" :model="form" label-width="100px" style="text-align: center;padding-bottom:10px">

    <el-upload :headers="headers" class="avatar-uploader" :action="getServerUrl() + '/user/uploadImage'"
      :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>

    <el-button @click="handleConfirm">确认更换</el-button>

  </el-form>


</template>

<script setup>

import { ref } from "vue";
import requestUtil, { getImageUrl, getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus'
import { useStore } from "@/store/piniaIndex"

const userStore = useStore();
//设置请求头
const headers = ref({
  Authorization: userStore.GET_TOKEN()
})

// 定义from表单
const form = ref(userStore.GET_USERINFO())
const formRef = ref(null)
//定义图片
const imageUrl = ref(getImageUrl() + form.value.avatar);

//上传事件
const handleAvatarSuccess = (res) => {
  let data = res.data;
  if (res.code == 1) {
    imageUrl.value = getImageUrl() + data.title;
    form.value.avatar = data.title;
    ElMessage.success("执行成功！")
  } else {
    ElMessage.error(res.message);
  }
}

//提交按钮
const handleConfirm = async () => {
  let result = await requestUtil.post("/user/updateAvatar", form.value);
  let data = result.data;
  if (data.code == 1) {
    ElMessage.success("执行成功！")
    userStore.SET_USERINFO(form.value)
  } else {
    ElMessage.error(data.message);
  }

}


//上传规则
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2M!')
  }
  return isJPG && isLt2M
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
